#include "binarytree.h";
#include "queue.h";

BinaryTree* binaryTree_createNode(int val)
{
    BinaryTree *res = NULL;
    
    res = malloc(sizeof(BinaryTree));
    
    if(res != NULL)
    {
        BinaryTree tmp = {0};
        *res = tmp;
        
        res -> value = val;
    }
    else
    {
        fprintf(stderr, "Allocation impossible");
        //exit(EXIT_FAILURE);
    }
    
    return res;
}

int binaryTree_isEmpty(BinaryTree *tree)
{
    return tree == NULL;
}

void binaryTree_preorderTraversal(BinaryTree  *tree)
{
    printf("%d ", tree->value);
    
    if(binaryTree_isEmpty(tree->Left) == 0)
        binaryTree_preorderTraversal(tree->Left);
    
    if(binaryTree_isEmpty(tree->Right) == 0)
        binaryTree_preorderTraversal(tree->Right);

}

void binaryTree_inorderTraversal(BinaryTree *tree)
{
    if(binaryTree_isEmpty(tree->Left)==0)
        binaryTree_inorderTraversal(tree->Left);
    
    printf("%d ", tree->value);
    
    if(binaryTree_isEmpty(tree->Right)==0)
        binaryTree_inorderTraversal(tree->Right);
}

void binaryTree_postorderTraversal(BinaryTree *tree)
{
    if(binaryTree_isEmpty(tree->Left) == 0)
        binaryTree_postorderTraversal(tree->Left);
    
    if(binaryTree_isEmpty(tree->Right) == 0)
        binaryTree_postorderTraversal(tree->Right);
    
    printf("%d ", tree->value);
}


void binaryTree_breadthTraversal(BinaryTree *tree)
{
    Queue *suite = NULL;
    suite = (Queue *) malloc (sizeof (Queue));
    init(suite);
    BinaryTree *node = NULL;
    enqueue(suite, NULL, tree);
    
    while(suite->size != 0)
    {
        node = dequeue(suite);
        printf("%d ", node->value);
        if(binaryTree_isEmpty(node->Left) == 0)
            enqueue(suite, suite->last, node->Left);
        
        if(binaryTree_isEmpty(node->Right) == 0)
            enqueue(suite, suite->last, node->Right);
    }
}
